﻿using Eatime.Entitys;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Reflection;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Threading.Tasks;

namespace Eatime.DataServiceProxy
{
    public class DataServicesProxy
    {
        string url = ApplicationConfigure.BaseUrl; 

        public T GetDatas<T, TParams>(TParams tParams, HttpMethod method, string requestPath)
        {
            Uri uri = new Uri(url);

            HttpClient client = new HttpClient();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            client.DefaultRequestHeaders.AcceptEncoding.Add(new StringWithQualityHeaderValue("utf-8"));

            if (method == HttpMethod.Get)
            {
                uri = new Uri(string.Format("{0}{1}?{2}", url, requestPath, BuildParams<TParams>(tParams)));
                return ExecuteResult<T>(client.GetStringAsync(uri).Result);
            }
            else if (method == HttpMethod.Post)
            {
                uri = new Uri(string.Format("{0}{1}", url, requestPath));
                return ExecuteResult<T>(client.PostAsync(uri, GetHttpContent<TParams>(tParams)).Result.Content.ReadAsStringAsync().Result);
            }

            return default(T);
        }

        private T ExecuteResult<T>(string result)
        {
           return JsonConvert.DeserializeObject<T>(result);
        }

        string BuildParams<TParams>(TParams tParams,bool isJson=false)
        {
            StringBuilder _result_ = new StringBuilder();
            int count = 0;

            if (isJson)
            {
                return JsonConvert.SerializeObject(tParams);
            }
            
            IEnumerable<PropertyInfo> propertyInfos = tParams.GetType().GetRuntimeProperties();
            foreach (PropertyInfo property in propertyInfos)
            {
                _result_.Append(string.Format("{0}={1}", property.Name, property.GetValue(tParams)));
                if (count < propertyInfos.Count())
                {
                    _result_.Append("&");
                    count++;
                }
            }
            return _result_.ToString();
        }

        HttpContent GetHttpContent<TParams>(TParams tParams)
        {
            var request = new StringContent(BuildParams(tParams, true), Encoding.UTF8, "application/json");
            return request;
        }
    }
}
